<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row class="elrow">
        <el-col>
          <el-button type="primary" @click="dialogVisible = true">
            添加角色
          </el-button>
        </el-col>
      </el-row>

      <!-- 角色列表展示区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdcol', il === 0 ? 'btcol' : '', 'vcenter']"
              v-for="(item1, il) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级列表 -->
              <el-col :span="5"
                ><el-tag closable @close="closeRoleById(scope.row, item1.id)"
                  >{{ item1.authName }}
                  <i class="el-icon-caret-right"></i>
                </el-tag>
              </el-col>
              <!-- 渲染二级列表和三级列表 -->
              <el-col :span="19">
                <el-row
                  :class="['bdcol', i2 === 0 ? '' : 'btcol', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6" type="success"
                    ><el-tag
                      type="success"
                      closable
                      @close="closeRoleById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="closeRoleById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{ scope.row }} 
            </pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-search"
              @click="editDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-search"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-search"
              @click="setRoleRightVisible(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 点击添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogVisible"
      width="50%"
      @close="DialogClosed()"
    >
      <el-form
        :model="addrolesList"
        :rules="rolesListRules"
        ref="rolesListRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addrolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addrolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 点击修改角色 -->
    <el-dialog
      title="修改角色信息"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form
        ref="editFormRef"
        :rules="editFormRules"
        :model="editForm"
        label-width="90px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 点击分配权限 -->
    <el-dialog
      title="提示"
      :visible.sync="showRightdialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defaultkey"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 点击分配权限对话框显示或隐藏
      showRightdialogVisible: false,
      // 用于储存所有权限列表
      rightList: [],
      //  树形控件的绑定对象
      treeProps: {
        children: "children",
        label: "authName",
      },
      // 展开树形控件 默认展开的key
      defaultkey: [],
      //   添加的角色信息
      addrolesList: {
        roleName: "",
        roleDesc: "",
      },
      //   控制添加角色对话框是否显示
      dialogVisible: false,
      // 分配权限列表 的角色id
      roleId:'',
      //    表单验证
      rolesListRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      //   控制修改jues对话框是否显示
      editDialogVisible: false,
      //   编辑用户对象
      editForm: {},
      editFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getRolesList();
  },

  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      // console.log(res);
      if (res.meta.status !== 200) {
        this.$Message.error("获取角色列表失败");
      }
      // 获取角色列表成功
      this.rolesList = res.data;
      this.$Message.success("获取角色列表成功");
    },
    // addRoles 监听对话框确定按钮
    addRoles() {
      this.$refs.rolesListRef.validate(async (valid) => {
        //     //  valid 是个布尔值
        console.log(valid);
        if (!valid) return;
        this.dialogVisible = false;
        //  如果预验证正确，发起网络请求
        const { data: res } = await this.$http.post("roles", this.addrolesList);
        // console.log(res);

        // 发送网络请求成功
        if (res.meta.status !== 201) return this.$Message.error("添加角色失败");
        this.$Message.success("添加角色成功");
        this.dialogVisible = false;
        this.getRolesList();
      });
    },
    // 监听对话框关闭
    DialogClosed() {
      this.$refs.rolesListRef.resetFields();
    },
    // 监听编辑角色按钮
    async editDialog(id) {
      // console.log(id+"1");
      const { data: res } = await this.$http.get("roles/" + id);
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$Message.error("根据id查询角色失败");
      this.$Message.success("根据id查询角色成功");
      //  给修改的对象赋值
      this.editForm = res.data;
      //  让对话框显示
      this.editDialogVisible = true;
    },
    // 监听弹出对话框
    editRolesInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return this.$Message.error("修改角色失败");

        // 发送网络请求
        const { data: res } = await this.$http.put(
          "roles/" + this.editForm.roleId,
          { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc }
        );
        // console.log(res);
        if (res.meta.status !== 200) {
          return this.$Message.error("修改角色失败");
        }
        //  修改角色成功
        // 1.刷新列表
        this.getRolesList();
        // 2.关闭对话框
        this.editDialogVisible = false;
        // 提出修改成功提示框
        this.$Message.success("修改角色成功");
      });
    },
    // 监听删除按钮
    async deleteRoles(id) {
      const delRole = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(delRole);
      if (delRole !== "confirm") {
        return this.$Message.info("已经取消删除角色");
      }
      const { data: res } = await this.$http.delete("roles/" + id);
      // console.log(res);
      // 1.刷新数据
      this.getRolesList();
      // 2.提示删除角色成功
      this.$Message.success("删除角色成功");
    },
    // 关闭权限
    async closeRoleById(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$Message.info("取消删除权限！");
      }

      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) return this.$Message.error("删除权限失败！");
      // 删除成功重新刷新页面
      role.children = res.data;
      // this.getRolesList()
    },
    // 监听点击分配权限事件
    async setRoleRightVisible(role) {
      this.roleId = role.id
      // 获取所有权限列表
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$Message.error("获取权限数据失败");
      }
      // console.log(res);
      this.rightList = res.data;
      // 获取三级权限
      this.getRightDialogId(role, this.defaultkey);
      console.log(this.defaultkey);
      // 显示对话框
      this.showRightdialogVisible = true;
    },
    // 使用递归方法获取三级节点下的权限id
    getRightDialogId(node, arr) {
      if (!node.children) {
        // 三级字节点下没有children
        return arr.push(node.id);
      }
      // 不是三级子节点，
      node.children.forEach((item) => {
        this.getRightDialogId(item, arr);
      });
    },
    // 监听关闭权限，重新清空数组
    setRightDialogClosed() {
      this.defaultkey = [];
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
     const idStr =  keys.join(",")
   const {data:res}= await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
      if(res.meta.status!==200){
          return this.$Message.error("角色授权失败")
      }
      this.$Message.success("角色授权成功")
      // 刷新数据 关闭对黄框
      this.getRolesList();
      this.showRightdialogVisible = false
    },
  },
};
</script>

<style scoped>
.elrow {
  margin-bottom: 15px;
}
.el-table {
  font-size: 12px;
}

.el-tag {
  margin: 7px;
}
.bdcol {
  border-bottom: 1px solid #eee;
}

.btcol {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>